﻿using BattleServer.Battle;
using PECommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BattleServer
{
    /// <summary>
    /// 游戏世界-对应主城地图，副本地图
    /// </summary>
    public class SWorld : SLogicBase
    {
        public WorldContainer Container { get; set; }
        public bool IsDestroy { get; set; } //场景中是否需要销毁

        /// <summary>
        /// 缓存SWorld中所有挂载的组件 key:组件的Hashcode value：comp自身
        /// </summary>
        private readonly Dictionary<int, SWorldComp> mCompDic = new Dictionary<int, SWorldComp>();
        public readonly ulong WorldID;

        public SWorld(ulong worldID)
        {
            WorldID = worldID;
        }

        /// <summary>
        /// 尝试进入游戏世界，会存在不同线程多人玩家同时进入，需添加到队列中操作
        /// </summary>
        /// <param name="worldID"></param>
        public virtual void TryEnterGameWorld(SUnitRole role)
        {
            
        }

        /// <summary>
        /// 挂载组件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T AddComp<T>() where T : SWorldComp, new()
        {
            T comp = new T();
            comp.Parent = this;
            if (comp is IAwake awakeComp) mAwakeList.Add(awakeComp);
            if(comp is IUpdate updateComp) mUpdateList.Add(updateComp);
            if(comp is IDestory destoryComp) mDestroyList.Add(destoryComp);
            int hashcode = comp.GetHashCode();
            if (!mCompDic.ContainsKey(hashcode))
            {
                mCompDic.Add(hashcode, comp);
            }
            return comp;
        }

        /// <summary>
        /// 获取组件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetComp<T>() where T : SWorldComp, new()
        {
            int hashcode = typeof(T).GetHashCode();
            if (mCompDic.ContainsKey(hashcode))
            {
                SWorldComp comp = mCompDic[hashcode];
                if (comp != null && comp is T)
                {
                    return comp as T;
                }
            }
            else
            {
                this.Error($"Get this comp [{typeof(T)}] is not exist!");
            }
            return null;
        }

        public void SetWorldDestroy()
        {
            IsDestroy = true;
        }

    }

    public enum SWorldCompType
    {
        None = 0,
        Nav, //地图导航组件
        Balance, //负载均衡组件
        AOIMgr, //AOI视野管理组件
        ResMonster, //公共地图资源怪物组件
    }
    public abstract class SWorldComp
    {
        public SWorld Parent;
        public SWorldCompType CompType;


        public T AddComp<T>() where T : SWorldComp, new()
        {
           return Parent.AddComp<T>();
        }


        
    }
}
